document.getElementById('rejectButton').addEventListener('click', () => {
  chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
    if (chrome.runtime.lastError) {
      console.error('Error querying tabs:', chrome.runtime.lastError);
      return;
    }
    
    if (tabs.length === 0 || !tabs[0].id) {
      console.error('No active tab found');
      return;
    }

    console.log('Sending rejectClicked message to background.js', tabs[0].id);
    
    chrome.runtime.sendMessage({
      action: 'rejectClicked', 
      tabId: tabs[0].id
    }, () => {
      // Close the popup after sending message
      window.close();
    });
  });
});

//处理rejectAllButton, 拒绝所有调价对话框
document.getElementById('rejectAllButton').addEventListener('click', () => {
  chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
    if (chrome.runtime.lastError) {
      console.error('Error querying tabs:', chrome.runtime.lastError);
      return;
    }
    if (tabs.length === 0 || !tabs[0].id) {
      console.error('No active tab found');
      return;
    }
    
    console.log('Sending rejectAllClicked message to background.js', tabs[0].id);
    
    chrome.runtime.sendMessage({
      action: 'rejectAllAdjustment', 
      tabId: tabs[0].id
    }, () => {
      // Close the popup after sending message
      window.close();
    });
  });
});

document.getElementById('closeMessageButton').addEventListener('click', () => {
  chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
    if (chrome.runtime.lastError) {
      console.error('Error querying tabs:', chrome.runtime.lastError);
      return;
    }
    
    if (tabs.length === 0 || !tabs[0].id) {
      console.error('No active tab found');
      return;
    }

    console.log('Sending closeMessageClicked message to background.js', tabs[0].id);
    
    chrome.runtime.sendMessage({
      action: 'closeMessageClicked', 
      tabId: tabs[0].id
    }, () => {
      // Close the popup after sending message
      window.close();
    });
  });
});

document.getElementById('sumRealtimeSold').addEventListener('click', () => {
  chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
    if (chrome.runtime.lastError) {
      console.error('Error querying tabs:', chrome.runtime.lastError);
      return;
    }
    
    if (tabs.length === 0 || !tabs[0].id) {
      console.error('No active tab found');
      return;
    }

    console.log('Sending sumRealtimeSoldClicked message to background.js', tabs[0].id);
    
    chrome.runtime.sendMessage({
      action: 'sumRealtimeSoldClicked', 
      tabId: tabs[0].id
    }, () => {
      // Close the popup after sending message
      window.close();
    });
  });
});

document.getElementById('adjustPriceButton').addEventListener('click', () => {
  console.log('Sending adjustPriceClicked message to background.js');
  
  chrome.runtime.sendMessage({
    action: 'adjustPriceClicked'
  }, () => {
    // Close the popup after sending message
    window.close();
  });
});

chrome.runtime.onMessage.addListener((message) => {
  if (message.action === 'showMongoDBUpdateComplete') {
    alert(`MongoDB外网接口更新完成！成功更新${message.successCount}/${message.totalServers}个服务器。`);
  }
  else if (message.action === 'reloginSellerStarted') {
    alert(`成功启动${message.successCount}/${message.totalServers}个服务器重新登录！`);
  }
  else if (message.action === 'fetchSalesDataComplete') {
    alert(`抓取销售数据完成！成功启动${message.successCount}/${message.totalServers}个服务器销售数据抓取。`);
  }
  else if (message.action === 'startDailyCrawlComplete') {
    alert(`启动每日抓取完成！成功启动${message.successCount}/${message.totalServers}个服务器数据抓取。`);
  }
  else if (message.action === 'restartServerTaskComplete') {
    alert(`重启服务器任务完成！成功启动${message.successCount}/${message.totalServers}个服务器任务。`);
  }
  else if (message.action === 'pullTemuSpidersComplete') {
    alert(`拉取TemuSpiders代码完成！成功在${message.successCount}/${message.totalServers}个服务器上拉取代码。`);
  }
});

document.getElementById('updateMongoDBButton').addEventListener('click', () => {
  chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
    if (chrome.runtime.lastError) {
      console.error('Error querying tabs:', chrome.runtime.lastError);
      return;
    }
    
    if (tabs.length === 0 || !tabs[0].id) {
      console.error('No active tab found');
      return;
    }

    const requiredUrl = 'http://192.168.0.142:9200/#/status/online';
    if (tabs[0].url !== requiredUrl) {
      alert('请先切换到网址: ' + requiredUrl);
      return;
    }

    console.log('Sending updateMongoDBLinkClicked message to background.js', tabs[0].id);
  
    chrome.runtime.sendMessage({
      action: 'updateMongoDBLinkClicked'
    }, () => {
      // Close the popup after sending message
      // window.close();
    });
  });
});

document.getElementById('reloginSellerButton').addEventListener('click', () => {
  console.log('Sending reloginSellerClicked message to background.js');
  
  chrome.runtime.sendMessage({
    action: 'reloginSellerClicked'
  }, () => {
    // Close the popup after sending message
    // window.close();
  });
});

document.getElementById('restartServerButton').addEventListener('click', () => {
  console.log('Sending restartServerClicked message to background.js');
  
  chrome.runtime.sendMessage({
    action: 'restartServerClicked'
  }, () => {
    // Close the popup after sending message
    // window.close();
  });
});

document.getElementById('getSalesDataButton').addEventListener('click', () => {
  console.log('Sending getSalesDataClicked message to background.js');
  
  chrome.runtime.sendMessage({
    action: 'getSalesDataClicked'
  }, () => {
    // Close the popup after sending message
    // window.close();
  });
});

document.getElementById('startDailyCrawlButton').addEventListener('click', () => {
  console.log('Sending startDailyCrawlClicked message to background.js');
  
  chrome.runtime.sendMessage({
    action: 'startDailyCrawlClicked'
  }, () => {
    // Close the popup after sending message
    // window.close();
  });
});

document.getElementById('pullTemuSpidersButton').addEventListener('click', () => {
  console.log('Sending pullTemuSpidersClicked message to background.js');
  
  chrome.runtime.sendMessage({
    action: 'pullTemuSpidersClicked'
  }, () => {
    // Close the popup after sending message
    // window.close();
  });
});

document.getElementById('previewAllPagesButton').addEventListener('click', () => {
  setTimeout(() => { 
    window.close();
  }, 1000);
  chrome.runtime.sendMessage({
    action: 'previewAllPagesClicked', 
  }, () => {
    // Close the popup after sending message
    window.close();
  });
});

// 自动拒绝调价功能
document.addEventListener('DOMContentLoaded', function() {
  const autoRejectCheckbox = document.getElementById('autoRejectCheckbox');
  
  // 从本地存储中读取设置
  if (typeof chrome !== 'undefined' && chrome.storage && chrome.storage.local) {
    chrome.storage.local.get(['autoRejectAdjustment'], function(result) {
      autoRejectCheckbox.checked = result.autoRejectAdjustment === true;
    });
  } else {
    console.error('Chrome存储API不可用，无法获取自动拒绝调价设置');
    autoRejectCheckbox.checked = false;
  }
  
  // 监听复选框变化
  autoRejectCheckbox.addEventListener('change', function() {
    if (typeof chrome !== 'undefined' && chrome.storage && chrome.storage.local) {
      chrome.storage.local.set({ autoRejectAdjustment: this.checked }, function() {
        console.log('自动拒绝调价设置已保存:', autoRejectCheckbox.checked);
        
        // 通知 contentScript.js 设置已更改
        if (chrome.tabs) {
          chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
            if (tabs.length > 0 && tabs[0].id) {
              chrome.tabs.sendMessage(tabs[0].id, { 
                action: 'autoRejectSettingChanged', 
                enabled: autoRejectCheckbox.checked 
              });
            }
          });
        }
      });
    } else {
      console.error('Chrome存储API不可用，无法保存自动拒绝调价设置');
    }
  })
});

document.getElementById('addSerialNumberButton').addEventListener('click', function() {
    const spuIdsInput = prompt('请输入商品spuId列表（逗号或换行符分隔）：');
    const serialNumberInput = prompt('请输入新的serial number：');

    if (!spuIdsInput || !serialNumberInput) {
        alert('输入不能为空！');
        return;
    }

    // 检查spuId列表
    const spuIds = spuIdsInput.split(/[,\n]/).map(id => id.trim()).filter(id => id);
    const isSpuIdsValid = spuIds.every(id => /^\d+$/.test(id));
    if (!isSpuIdsValid || spuIds.length === 0) {
        alert('spuId列表格式错误：必须为逗号或换行符分隔的全数字字符串，且不能为空！');
        return;
    }

    // 检查serial number
    const serialNumber = serialNumberInput.trim();
    if (!serialNumber || /\s/.test(serialNumber)) {
        alert('serial number格式错误：去除前后空格后不能为空，且中间不能包含空格！');
        return;
    }

    // 发送消息给runtime
    const uniqueSpuIds = [...new Set(spuIds)]; // 去重
    chrome.runtime.sendMessage({
        action: 'addSerialNumber',
        spuIds: uniqueSpuIds,
        serialNumber: serialNumber
    }, function(response) {
        if (response && response.success) {
            alert('操作成功！');
        } else {
            alert('操作失败：' + (response.error || '未知错误'));
        }
    });
});